package com.yfq.springframework.beans.support;

import com.yfq.springframework.beans.BeansException;
import com.yfq.springframework.beans.FactoryBean;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: yfq
 * @date: 2023/1/31 14:36
 * @description: 处理FactoryBean类型bean的注册操作
 */
public class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
    /**
     * Cache of singleton objects created by FactoryBeans: FactoryBean name to object.
     */
    private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>(16);

    public Object getCachedObjectForFactoryBean(String beanName) {
        return factoryBeanObjectCache.get(beanName);
    }

    public Object getObjectFromFactoryBean(FactoryBean<?> factoryBean, String beanName) {
        if (factoryBean.isSingleton()) {
            Object bean = getCachedObjectForFactoryBean(beanName);
            if (bean == null) {
                //创建bean，放入到缓存
                bean = doGetObjectFromFactoryBean(factoryBean, beanName);
                factoryBeanObjectCache.put(beanName, bean);
            }
            return bean;
        }

        return doGetObjectFromFactoryBean(factoryBean, beanName);
    }

    public Object doGetObjectFromFactoryBean(FactoryBean<?> factoryBean, String beanName) {
        try {
            return factoryBean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BeansException("FactoryBean threw exception on object[" + beanName + "] creation");
        }
    }
}
